//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package client_cfg_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas/api-server/config"
	"atomgit.com/openlinksaas/api-server/dao/client_cfg_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/client_cfg_api"
	"go.uber.org/zap"
)

type ClientCfgApiImpl struct {
	client_cfg_api.UnimplementedClientCfgApiServer
	servCfg   *config.ServerConfig
	errLogger *zap.Logger
}

func NewClientCfgApiImpl(servCfg *config.ServerConfig, errLogger *zap.Logger) *ClientCfgApiImpl {
	return &ClientCfgApiImpl{
		servCfg:   servCfg,
		errLogger: errLogger,
	}
}

func (apiImpl *ClientCfgApiImpl) GetCfg(ctx context.Context, req *client_cfg_api.GetCfgRequest) (*client_cfg_api.GetCfgResponse, error) {
	menuItemList, err := client_cfg_dao.ExtraMenuDao.List(ctx)
	if err != nil {
		return nil, err
	}
	itemList := []*client_cfg_api.ExtraMenuItem{}
	for _, menuItem := range menuItemList {
		itemList = append(itemList, menuItem.ToExtraMenuItem())
	}

	return &client_cfg_api.GetCfgResponse{
		ItemList: itemList,
		ServerCap: &client_cfg_api.ServerCap{
			ProjectDoc:     true,
			Sprit:          true,
			Issue:          true,
			ProjectSetting: true,
		},
		EnableAdmin:     apiImpl.servCfg.Admin.Enable,
		AtomGitClientId: apiImpl.servCfg.AtomGit.ClientId,
		GiteeClientId:   apiImpl.servCfg.Gitee.ClientId,
		JihulabClientId: apiImpl.servCfg.Jihulab.ClientId,
		GitCodeClientId: apiImpl.servCfg.GitCode.ClientId,
		ServerTime:      time.Now().UnixNano() / 1e6,
		DisableLogin:    apiImpl.servCfg.ClientCfg.DisableLogin,
	}, nil
}

func (apiImpl *ClientCfgApiImpl) ReportError(ctx context.Context, req *client_cfg_api.ReportErrorRequest) (*client_cfg_api.ReportErrorResponse, error) {
	if apiImpl.errLogger != nil {
		apiImpl.errLogger.Info(req.ErrData)
	}
	return &client_cfg_api.ReportErrorResponse{}, nil
}
